package com.team.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.team.entity.Project;
import com.team.entity.User;
import com.team.entity.UserProject;
import com.team.util.DbHelp;
import com.team.util.ResultSetPackge;

public class UserProjectDao {

	DbHelp<UserProject> db = new DbHelp<UserProject>();
	
	/**
	 * insert into t_user_project userid and projectid and role
	 * @param user
	 * @param project
	 * @return
	 */
	 public int saveUserAndProject(User user,Project project,String role){
		 String sql = "insert into t_user_project(t_user_id,t_project_id,role)values(?,?,?)";
		 return db.executeUpdateSql(sql, user.getId(),project.getId(),role);
	 }
	 
	 public List<UserProject> selectByProjId(int projId){
		 String sql = "select id,t_user_id,t_project_id,role from t_user_project where t_project_id = ?";
		 return db.exeSelectForList(sql, new PackgeUserProject(), projId);
	 }
	 
	 
	 
	 private class PackgeUserProject implements ResultSetPackge<UserProject>{

		public UserProject packgeResultSet(ResultSet rs) throws SQLException {
			UserProject up = new UserProject();
			up.setUserId(rs.getInt("t_user_id"));
			up.setProjId(rs.getInt("t_project_id"));
			up.setRole(rs.getString("role"));
			up.setId(rs.getInt("id"));
			return up;
		}
		 
	 }

	public int updateUserAndProject(User user, int projectId, String string) {
		String sql = "update t_user_project set t_user_id = ? where t_project_id = ? and role = ?";
		 return db.executeUpdateSql(sql, user.getId(),projectId,string);
	}

	public int updateByIdAndUser(int id, User user) {
		String sql = "update t_user_project set t_user_id = ? where id = ?";
		return db.executeUpdateSql(sql, user.getId(),id);
		
	}

	public List<UserProject> selectByProjIdAndRole(int projectId, String string) {
		 String sql = "select id,t_user_id,t_project_id,role from t_user_project where t_project_id = ? and role =  ?";
		 return db.exeSelectForList(sql, new PackgeUserProject() , projectId,string);
	}

	public int updateUserAndUserProject(UserProject up, User user) {
		String sql = "update t_user_project set t_user_id = ? where id = ?";
		return db.executeUpdateSql(sql,user.getId(),up.getId());
		
	}
	
	
}
